//
//  Popup.swift
//  yuejian
//
//  Created by gyy on 2017/11/3.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit

class Popup: UIViewController {

    private var strongSelf:Popup!
    private var label:UILabel!
    private var action:(()->Void)?
    
    init(){
        super.init(nibName: nil, bundle: nil)
        strongSelf = self
        initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func appear(title:String,action:(()->Void)?){
        self.action = action
        self.label.text = title
        UIApplication.shared.keyWindow?.addSubview(self.view)
    }
    
    private func initialize(){
        view.backgroundColor = .clear
        
        let backgroundLayer = CAShapeLayer()
        backgroundLayer.opacity = 0.4
        backgroundLayer.backgroundColor = UIColor.black.cgColor
        backgroundLayer.frame = view.bounds
        view.layer.addSublayer(backgroundLayer)
        
        let rectangle = CAShapeLayer()
        rectangle.backgroundColor = UIColor.white.cgColor
        rectangle.frame = CGRect(x: 52.5, y: 281.5, width: 270, height: 104.5)
        rectangle.cornerRadius = 12
        let line = CAShapeLayer()
        line.frame = CGRect(x: 0, y: 60, width: 270, height: 0.5)
        line.backgroundColor = UIColor.lightGray.cgColor
        rectangle.addSublayer(line)
        view.layer.addSublayer(rectangle)
        
        label = UILabel(frame: CGRect(x: 52.5, y: 20+281.5, width: 270, height: 20.5))
        label.font = UIFont.boldSystemFont(ofSize: 17)
        label.textAlignment = .center
        view.addSubview(label)
        
        let button = UIButton(frame: CGRect(x: 52.5, y: 60.5+281.5, width: 270, height: 44))
        button.setTitle("确认", for: .normal)
        button.setTitleColor(.black, for: .normal)
        view.addSubview(button)
        
        button.addTarget(self, action: #selector(disappear), for: .touchUpInside)
    }
    
    @objc func disappear(){
        if action != nil{
            action!()
        }
        strongSelf = nil
        view.removeFromSuperview()
    }
    
    deinit {
        print("deinit")
    }
}

